//
//  ListView.m
//  Foundation
//
//  Created by 新庭 on 2019/6/2.
//

#import "ListView.h"
#import <FFoundation/FXCategories.h>

static CGFloat kDefaultListViewCellHeight = 44.f;
@interface ListView () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, assign) CGFloat autoWidth;

@end

@implementation ListView

+ (ListView *)listViewWith:(nullable NSArray *)items andCell:(nullable Class)cellClass {
    ListView *view = [[ListView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    view.cellClass = cellClass;
    [view setup];
    
    NSMutableArray *mArr = [NSMutableArray array];
    [items enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [mArr addObject:[ListItem itemWith:obj]];
    }];
    view.items = mArr;
    
    return view;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    if (self = [super initWithFrame:frame style:style]) {
        [self setup];
    }
    return self;
}

- (void)setup {
    self.font = [UIFont systemFontOfSize:UIFont.systemFontSize];
    self.delegate = self;
    self.dataSource = self;
    self.separatorInset = UIEdgeInsetsZero;
    self.tableFooterView = [UIView new];
    if (!self.cellClass) {
        self.cellClass = UITableViewCell.class;
    }
    self.clipsToBounds = YES;
}

- (void)setCellClass:(Class)cellClass {
    _cellClass = cellClass;
    
    if (cellClass) {
        [self registerClass:cellClass forCellReuseIdentifier:NSStringFromClass(cellClass)];
    }
}

- (NSUInteger)selectedIndex {
    return [self indexPathForSelectedRow].row;
}

- (void)setSelectedIndex:(NSUInteger)selectedIndex {
    [self selectRowAtIndexPath:[NSIndexPath indexPathForRow:selectedIndex inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
}

- (ListItem *)selectedItem {
    return [self.items objectAtIndex:self.selectedIndex];
}

- (CGSize)intrinsicContentSize {
    CGFloat height = kDefaultListViewCellHeight;
    if (self.rowHeight > 0) {
        height = self.rowHeight;
    }
    return CGSizeMake(self.autoWidth, self.items.count * height);
}

- (void)reloadData {
    [self invalidateIntrinsicContentSize];
    [super reloadData];
}

#pragma mark - Table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.items.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ListItem *item = [self.items objectAtIndex:indexPath.row];
    if (![self.cellClass isEqual:UITableViewCell.class]) {
        UITableViewCell<ListCellProtocol> *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(self.cellClass) forIndexPath:indexPath];
        [cell updateWithItem:item];
        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(UITableViewCell.class) forIndexPath:indexPath];
        cell.textLabel.font = self.font;
        NSString *title = [NSString stringWithFormat:@"%@", item.item];
        if (self.titleFormater) {
            title = self.titleFormater(item);
        }
        cell.textLabel.text = title;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    !self.onSelect ?: self.onSelect(self);
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Private
- (CGFloat)autoWidth {
    if (_autoWidth <= 0) {
        for (ListItem *item in self.items) {
            NSString *title = [NSString stringWithFormat:@"%@", item.item];
            if (self.titleFormater) {
                title = self.titleFormater(item);
            }
            
            CGFloat width = [title jk_sizeWithFont:self.font constrainedToWidth:UIScreen.jk_width].width;
            _autoWidth = MAX(width, _autoWidth);
        }
    }
    return _autoWidth + 50; // uitableviewcell 边距
}

@end
